package com.lijiaxing.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.Map;

public class JwtMaker {
    private static JWTCreator.Builder jwtBuilder; //加密
    private static String sign_secret;//算法
    private static JWTVerifier jwtVerifier;//解密

    static {
        jwtBuilder = JWT.create();
        sign_secret = "skdfiuncmaqlzpi";
        jwtVerifier = JWT.require(Algorithm.HMAC256(sign_secret)).build();
    }

    /**
     * {
     *
     * @param claims 载荷
     * @param expire 有效期n天
     * @code
     * @description jwt加密
     * }
     */
    public static String enCoder(Map claims, int expire) {
        return jwtBuilder.withClaim("data", claims)
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * expire))
                .sign(Algorithm.HMAC256(sign_secret));
    }

    /**
     * {
     *
     * @return String 载荷
     * }
     * @throws com.auth0.jwt.exceptions.TokenExpiredException token过期
     * @code
     * @description jwt解密
     */
    public static Map deCoder(String token) {
        DecodedJWT verify = jwtVerifier.verify(token);
        return verify.getClaims();
    }
}
